package com.easy.dev.utils;

import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: 多语言国际化消息工具类
 * @Date 2020/07/22
 */
public class I18nMessageUtil {

    private static ConcurrentHashMap<String, ResourceBundle> messages = new ConcurrentHashMap<String, ResourceBundle>();


    private I18nMessageUtil(){
    }

    /**
     * @param key
     * @param defaultMessages
     * @return
     */
    public static String getMessage(String key, String defaultMessages) {
        // 获取语言，这个语言是从header中的Accept-Language中获取的，
        // 会根据Accept-Language的值生成符合规则的locale，如zh、pt、en等
        Locale locale = LocaleContextHolder.getLocale();
        ResourceBundle message = messages.get(locale.getLanguage());
        if (null == message) {
            synchronized (messages) {
                // 在这里读取配置信息
                message = messages.get(locale.getLanguage());
                if (null == message) {
                    message = ResourceBundle.getBundle("i18n/message", locale);
                    messages.put(locale.getLanguage(), message);
                }
            }
        }
        String msg = message.getString(key);
        return msg == null ? defaultMessages:msg;
    }

    /**
     * 清空错误文本缓存map
     */
    public static void flushMessage() {
        messages.clear();
    }
}

